﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using V5_Model;
using V5_Common;
using V5_DAL;
using System.IO;
using System.Web;

namespace V5_BLL
{
    public class BLLProduct
    {

        DALProduct dal = new DALProduct();
        #region  成员方法

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return dal.GetMaxId();
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int ID)
        {
            return dal.Exists(ID);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public void Add(ModelProduct model)
        {
            dal.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public void Update(ModelProduct model)
        {
            dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public void Delete(int ID)
        {

            dal.Delete(ID);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public ModelProduct GetModel(int ID)
        {

            return dal.GetModel(ID);
        }

        /// <summary>
        /// 得到一个对象实体，从缓存中。
        /// </summary>
        public ModelProduct GetModelByCache(int ID)
        {

            string CacheKey = "ModelProductModel-" + ID;
            object objModel = DataCache.GetCache(CacheKey);
            if (objModel == null)
            {
                try
                {
                    objModel = dal.GetModel(ID);
                    if (objModel != null)
                    {
                        int ModelCache = ConfigHelper.GetConfigInt("ModelCache");
                        DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
                    }
                }
                catch { }
            }
            return (ModelProduct)objModel;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }
        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            return dal.GetList(Top, strWhere, filedOrder);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<ModelProduct> GetModelList(string strWhere)
        {
            DataSet ds = dal.GetList(strWhere);
            return DataTableToList(ds.Tables[0]);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<ModelProduct> DataTableToList(DataTable dt)
        {
            List<ModelProduct> modelList = new List<ModelProduct>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                ModelProduct model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new ModelProduct();
                    if (dt.Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(dt.Rows[n]["ID"].ToString());
                    }
                    if (dt.Rows[n]["ChannelID"].ToString() != "")
                    {
                        model.ChannelID = int.Parse(dt.Rows[n]["ChannelID"].ToString());
                    }
                    if (dt.Rows[n]["ClassID"].ToString() != "")
                    {
                        model.ClassID = int.Parse(dt.Rows[n]["ClassID"].ToString());
                    }
                    model.ProductName = dt.Rows[n]["ProductName"].ToString();
                    model.ProductKeysWords = dt.Rows[n]["ProductKeysWords"].ToString();
                    model.ProductCode = dt.Rows[n]["ProductCode"].ToString();
                    model.ProductBrand = dt.Rows[n]["ProductBrand"].ToString();
                    model.ProductUnit = dt.Rows[n]["ProductUnit"].ToString();
                    model.ProductWeight = dt.Rows[n]["ProductWeight"].ToString();
                    model.ProductMarketPrice = dt.Rows[n]["ProductMarketPrice"].ToString();
                    model.ProductMemberPrice = dt.Rows[n]["ProductMemberPrice"].ToString();
                    model.ProductMinPrice = dt.Rows[n]["ProductMinPrice"].ToString();
                    model.ProductBigPic = dt.Rows[n]["ProductBigPic"].ToString();
                    model.ProductSmallPic = dt.Rows[n]["ProductSmallPic"].ToString();
                    model.ProductMorePic = dt.Rows[n]["ProductMorePic"].ToString();
                    if (dt.Rows[n]["ProductCount"].ToString() != "")
                    {
                        model.ProductCount = int.Parse(dt.Rows[n]["ProductCount"].ToString());
                    }
                    if (dt.Rows[n]["ProductFieldType"].ToString() != "")
                    {
                        model.ProductFieldType = int.Parse(dt.Rows[n]["ProductFieldType"].ToString());
                    }
                    model.ProductFields = dt.Rows[n]["ProductFields"].ToString();
                    model.ProductSingleFields = dt.Rows[n]["ProductSingleFields"].ToString();
                    model.ProductSizeTable = dt.Rows[n]["ProductSizeTable"].ToString();
                    if (dt.Rows[n]["IsPassed"].ToString() != "")
                    {
                        model.IsPassed = int.Parse(dt.Rows[n]["IsPassed"].ToString());
                    }
                    if (dt.Rows[n]["IsOnSale"].ToString() != "")
                    {
                        model.IsOnSale = int.Parse(dt.Rows[n]["IsOnSale"].ToString());
                    }
                    if (dt.Rows[n]["IsRecommond"].ToString() != "")
                    {
                        model.IsRecommond = int.Parse(dt.Rows[n]["IsRecommond"].ToString());
                    }
                    if (dt.Rows[n]["IsOnHot"].ToString() != "")
                    {
                        model.IsOnHot = int.Parse(dt.Rows[n]["IsOnHot"].ToString());
                    }
                    if (dt.Rows[n]["IsNew"].ToString() != "")
                    {
                        model.IsNew = int.Parse(dt.Rows[n]["IsNew"].ToString());
                    }
                    if (dt.Rows[n]["IsSpecialOffer"].ToString() != "")
                    {
                        model.IsSpecialOffer = int.Parse(dt.Rows[n]["IsSpecialOffer"].ToString());
                    }
                    if (dt.Rows[n]["Package"].ToString() != "")
                    {
                        model.Package = int.Parse(dt.Rows[n]["Package"].ToString());
                    }
                    model.ShortContent = dt.Rows[n]["ShortContent"].ToString();
                    model.Content = dt.Rows[n]["Content"].ToString();
                    model.ProductRelated = dt.Rows[n]["ProductRelated"].ToString();
                    if (dt.Rows[n]["Hits"].ToString() != "")
                    {
                        model.Hits = int.Parse(dt.Rows[n]["Hits"].ToString());
                    }
                    if (dt.Rows[n]["AddDateTime"].ToString() != "")
                    {
                        model.AddDateTime = DateTime.Parse(dt.Rows[n]["AddDateTime"].ToString());
                    }
                    if (dt.Rows[n]["UpDateTime"].ToString() != "")
                    {
                        model.UpDateTime = DateTime.Parse(dt.Rows[n]["UpDateTime"].ToString());
                    }
                    model.XjIDs = dt.Rows[n]["XjIDs"].ToString();
                    modelList.Add(model);
                }
            }
            return modelList;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(int PageSize, int PageIndex, string strWhere)
        {
            return dal.GetList(PageSize, PageIndex, strWhere);
        }

        #endregion  成员方法


        public DataSet GetList(int PageSize, int PageIndex, string strWhere, string strOrder, int isDesc, out int Count)
        {
            Count = Input.SetInt(this.GetList(strWhere).Tables[0].Rows.Count);
            return dal.GetList(PageSize, PageIndex, strWhere, strOrder, isDesc);
        }

        public ModelProduct GetModel(int ID, bool isChoice)
        {
            //增加产品字段
            ModelProduct model = this.GetModel(ID);
            if (isChoice)
            {
                if (Input.SetString(model.ProductFields) != "")
                {
                    model.Choicetable = new BLLProductField().GetProductCustomChoice(model.ProductFields);
                }
            }
            return model;
        }

        public DataSet GetList(int PageSize, int PageIndex, string strWhere, ref int recordCount)
        {
            recordCount = Input.SetInt(this.GetList(strWhere).Tables[0].Rows.Count);
            return dal.GetList(PageSize, PageIndex, strWhere);
        }

        public List<ModelProduct> GetModelList(int top, string strWhere, string orderStr)
        {
            DataSet ds = dal.GetList(top, strWhere, orderStr);
            return DataTableToList(ds.Tables[0]);
        }

        //产品编号
        public string GetProductNo(string productID, DateTime times)
        {
            string numberRule = "{Lead}{Time}{Number}|PN|yyMMddhhmmss|4";
            return GetProductNo(numberRule, productID, times);
        }
        //产品编号
        public string GetProductNo(string numberRule, string productID, DateTime times)
        {

            string[] strArray = numberRule.Split(new char[] { '|' });
            int length = productID.Length;
            string format = "yymmdd";
            string newValue = "";
            string str3 = times.ToString("yyyy-MM-dd");
            string str4 = "";
            try
            {
                newValue = strArray[1].Trim();
                format = strArray[2].Trim();
                length = int.Parse(strArray[3].Trim());
            }
            catch
            {
            }
            if (productID.Length > length)
            {
                str4 = productID.Remove(0, productID.Length - length);
            }
            else
            {
                for (int i = 0; i < (length - productID.Length); i++)
                {
                    str4 = str4 + "0";
                }
                str4 = str4 + productID;
            }
            try
            {
                str3 = times.ToString(format);
            }
            catch
            {
            }
            return strArray[0].Replace("{Lead}", newValue).Replace("{Time}", str3).Replace("{Number}", str4).Replace("{lead}", newValue).Replace("{time}", str3).Replace("{number}", str4);
        }
        //产品多图
        public DataTable Get_ProductMorePics(string productmorepics)
        {
            DataTable dt = new DataTable();
            if (productmorepics.Length > 0)
            {
                string[] strArray = productmorepics.Split(new string[] { "$$$$" }, StringSplitOptions.None);
                dt.Columns.Add(new DataColumn("id"));//索引
                dt.Columns.Add(new DataColumn("m1"));//图片说明
                dt.Columns.Add(new DataColumn("m2"));//图片地址
                int num = 0;
                foreach (string strpic in strArray)
                {
                    string[] str2 = strpic.Split(new string[] { "||" }, StringSplitOptions.None);
                    DataRow row = dt.NewRow();
                    row[0] = num;
                    row[1] = str2[0];
                    row[2] = str2[1];
                    dt.Rows.Add(row);
                    num++;
                }
                return dt;
            }
            return dt;
        }

        public void Delete(int ID, bool isdelother)
        {
            if (isdelother)
            {
                #region
                //删除图片
                //检查图片是否存在
                ModelProduct model = new BLLProduct().GetModel(ID);
                if (model != null)
                {
                    string path = HttpContext.Current.Server.MapPath("~/");
                    string bigPic = model.ProductBigPic.ToLower();
                    if (bigPic.Length > 0)
                    {
                        if (File.Exists(path + "/" + bigPic))
                        {
                            File.Delete(path + "/" + bigPic);//删除中图
                            File.Delete(path + "/" + bigPic.Replace("productm", "products"));//小图
                            File.Delete(path + "/" + bigPic.Replace("productm", "productl"));//大图
                        }
                    }
                    string morePics = model.ProductMorePic;
                    if (morePics.Length > 0)
                    {
                        foreach (string s1 in morePics.ToLower().Split(new string[] { "$$$$" }, StringSplitOptions.None))
                        {
                            string[] arrs1 = s1.Split(new string[] { "||" }, StringSplitOptions.None);
                            if (File.Exists(path + "/" + arrs1[1]))
                            {
                                File.Delete(path + "/" + arrs1[1]);//删除中图
                                File.Delete(path + "/" + arrs1[1].Replace("productm", "products"));//小图
                                File.Delete(path + "/" + arrs1[1].Replace("productm", "productl"));//大图
                            }
                        }
                    }
                }
                #endregion
            }
            dal.Delete(ID);
        }
    }
}
